package com.ruubypay.biz.mvc.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruubypay.biz.mvc.workflow.model.request.FlowModel;
import com.ruubypay.biz.mvc.workflow.service.ModelService;
import com.ruubypay.web.common.code.ResultCode;
import com.ruubypay.web.common.code.ResultEntity;
import com.ruubypay.web.common.page.DataGrid;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 工作流模型管理
 * @author chenhaiyang
 */
@Controller
@RequestMapping(value="/workflow/model/")
public class ModelController {

    private static Logger logger = LoggerFactory.getLogger(ModelController.class);

    @Resource
    private ModelService modelService;


    /**
     * 列表页跳转
     * @return 返回url
     */
    @RequestMapping(value = "/list" , method = RequestMethod.GET)
    public String listModels() {
        return "views/model/model_list";
    }

    /**
     * 跳转到流程编辑器
     * @return 返回视图
     */
    @RequestMapping(value = "/editor" , method = RequestMethod.GET)
    public ModelAndView view(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("views/model/editor");
        mv.addObject("moduleId",request.getParameter("moduleId"));
        return mv;
    }

    /**
     * 跳转到预览xml图页面
     * @return 返回视图
     */
    @RequestMapping(value = "/view" , method = RequestMethod.GET)
    public ModelAndView editor(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("views/model/model_xmlview");

        String modelId=request.getParameter("moduleId");
        mv.addObject("moduleId",modelId);
        try {
            String code = modelService.viewXmlFromModelId(modelId);
            mv.addObject("code",code);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return mv;
    }

    /**
     * 获取模型列表
     * @return 模型
     */
    @ResponseBody
    @RequestMapping(value="/list",method = RequestMethod.POST)
    public String list(HttpServletRequest request) {

        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("modelName",request.getParameter("modelName"));
        paramMap.put("category",request.getParameter("category"));
        Integer pageNumber = ServletRequestUtils.getIntParameter(request,"pageNumber",1);
        Integer pageSize = ServletRequestUtils.getIntParameter(request,"pageSize",10);

        DataGrid modelPage = null;
        try {
            modelPage = modelService.listDataModels(paramMap,pageNumber,pageSize);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return JSON.toJSONString(modelPage);
    }

    /**
     *
     * @param flowModel 流程模型
     * @return 返回执行结果
     */
    @ResponseBody
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(FlowModel flowModel){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        String modelId;
        try {
            modelId= modelService.saveModel(flowModel);
            resultEntity.setResData(modelId);
        } catch (Exception e) {
            resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
            logger.error(e.getMessage(),e);
        }
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 删除模型
     * @param request request
     * @return 返回删除结果
     */
    @ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public String delete(HttpServletRequest request){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        String idArray = request.getParameter("idArray");
        if (StringUtils.isNotBlank(idArray)) {
            try {
                int l = modelService.deleteModelService(idArray);
                resultEntity.setResData(l + "");
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 部署模型
     * @param flowModel 模型
     * @return 返回部署id
     */
    @ResponseBody
    @RequestMapping("deployment")
    public String deployment(FlowModel flowModel){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        if (StringUtils.isNotBlank(flowModel.getId())) {
            try {
                String deploymentId = modelService.deploymentModel(flowModel);
                resultEntity.setResData(deploymentId);
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 是否允许导出xml
     * @param flowModel 流程模型
     * @return 返回结果
     */
    @ResponseBody
    @RequestMapping("/canexport")
    public String canexport(FlowModel flowModel){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        if (StringUtils.isNotBlank(flowModel.getId())) {
            String isOk = modelService.isCanexportXmlFromModelId(flowModel);
            resultEntity.setResData(isOk);
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 根据模型id导出xml文件
     */
    @RequestMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String modelId = request.getParameter("modelId");
        if(StringUtils.isNotBlank(modelId)){
            Object[] results = modelService.exportXmlFromModelId(modelId);
            byte[] bpmnBytes = (byte[]) results[0];
            String fileName = (String) results[1];

            ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
            IOUtils.copy(in, response.getOutputStream());
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.flushBuffer();
            in.close();
        }
    }
}
